package com.hgvip.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by arnold.zhu on 6/8/2017.
 * <p>
 * 打印每次请求的参数和响应结果
 * </p>
 */
@Aspect
@Component
@Order(1)
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(* com.hgvip.controller..*(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
        Object[] obj = pjp.getArgs();
        if (!"GET".equals(request.getMethod())) {
            logger.info("RequestURI:" + request.getRequestURI() + " Request Arguments：" + JSON.toJSONString(obj[0]));
        } else {
            logger.info("RequestURI:" + request.getRequestURI());
        }
        Object result = pjp.proceed();
        logger.info("RequestSuccess Result：" + JSON.toJSONString(result));
        return result;
    }

}
